<?php

function __autoload($class)
{
	static $PATHS = null;

	if (is_null($PATHS))
	{
		$PATHS = array
		(
			'xptml' => array
			(
				XPTMLROOT . 'engine/',
				XPTMLROOT . 'module/',
				XPTMLROOT . 'interface/'
			)
		);

		if (AUTOLOAD)
		{
			$plugins = new DirectoryIterator(XPTMLROOT . 'plugin/');
			foreach ($plugins as $path)
			{
				if (in_array($path->getBasename(), array('.', '..'))) continue;
				if (! $path->isDir()) continue;
				$PATHS['xptml\\' . $path->getBasename()] = sprintf('%splugin/%s/module/', XPTMLROOT, $path->getBasename());
			}

			unset($plugins, $path);
		}
	};

	$depth = explode('\\', $class);

	if (count($depth) == 1)
	{
		$class = each($depth);
		$namespace = '\\';
	} elseif (count($depth) == 2)
	{
		list($namespace, $class) = $depth;
	} elseif (count($depth) > 2)
	{
		$class = array_pop($depth);
		$namespace = implode('\\', $depth);
	} else
	{
		throw new \InvalidArgumentException('Unexpected namespace/class pair');
	}

	unset($depth);

	if (! isset($PATHS[$namespace]))
	{
		throw new \DomainException(sprintf('Unexpected namespace path (%s)', $namespace));
	}

	foreach ($PATHS[$namespace] as $path)
	{
		if (file_exists($filename = "{$path}{$class}.php"))
		{
			require_once $filename;
			break;
		}
	}

}

?>